<?php
namespace app\admin\controller\nursinguser;;

use app\admin\model\NursingType;
use app\admin\model\TermEmergencyLang;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use app\admin\model\publicuse\PublicUse;
use smartybuilder\libs\Quickbuilder;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="长期护理")
 * Class Nursinglang
 */
class Nursinglang extends AdminController
{
    use \app\admin\traits\Curd;
     protected $allowModifyFields = [
        'status',
    ];
    protected $noExportFields = [
        'id',
        'name',
        'sort',
        'img',
        'banner',
        'home_money',
        'no_hoime_money',
        'duration',
        'type_id',
        'content',
        'create_time',
        'update_time',
        'status',
        'delete_time',
    ];
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\NursingLang();
        $array = PublicUse::getConfigDir(__CLASS__);
        if(is_file(__DIR__.DIRECTORY_SEPARATOR.'field'.DIRECTORY_SEPARATOR.$array['class'].'.txt')){
           $this->AllData = json_decode(file_get_contents(__DIR__.DIRECTORY_SEPARATOR.'field'.DIRECTORY_SEPARATOR.$array['class'].'.txt'),true);
        }
    }
    public function index()
    {
        $param = request()->param();
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames([],$this->AllData['field']??[]);
            if(isset($this->AllData['is_page'])&&$this->AllData['is_page']==0){
                $limit = 10000;
            }
            $where = PublicUse::getParameter($where);
//            $where[] = ['id','=',16];
            $count = $this->model
                ->where($where)
                ->count();
            try{
                $list = $this->model
                    ->where($where)
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select();
            }catch (\Exception $e){
                $list = $this->model
                    ->where($where)
                    ->page($page, $limit)
//                ->order($this->sort)
                    ->select();
            }
//            dump($list->toArray());die();
            $list = PublicUse::objctToModelAndField($list,$this->AllData['field']??[]);
//            dump($list);die();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $parameter = '';
        $fi = $this->model->getPk();
        if(!empty($param['field'])&&!empty($param[$fi])){
            $parameter = "?{$param['field']}={$param[$fi]}";
        }
        $newwhere = $this->request->get();
        foreach ($newwhere as $key=>$value){
            if($key!==$fi&&$key!=='field'){
                if(strpos($parameter,'?')===false){
                    $parameter .= "?{$key}={$value}";
                }else{
                    $parameter .= "&{$key}={$value}";
                }
            }
        }
//        echo $parameter;exit;
        $this->assign('parameter',$parameter);
        return $this->fetch();
    }
    public function delete()
    {
        $data = request()->param();
        $field = $this->model->getPk();
        if(!$field){
            $field = 'id';
        }
        if(!isset($data[$field])){
            return $this->error('请传入主键');
        }
        if($data[$field]==8){
            $this->error('本数据不可删除');
        }
        $row = $this->model->whereIn($field, $data[$field])->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="添加钟点工")
     */
    public function zhogndiangong(){
        $data = $this->request->param();
        $shuju = $this->model->where('status',1)
            ->where('type_id',$data['id'])
            ->find();
        if(empty($shuju)){
            $url = url('nursinguser.nursinglang/add?type_id='.$data['id'])->build();
        }else{
            $url = url('nursinguser.nursinglang/edit?id='.$shuju->id)->build();
        }
        return $this->redirect($url);
    }
    /**
     * @NodeAnotation(title="添加保姆")
     */
    public function baomu(){
        $data = $this->request->param();
        echo '<pre>';
        print_r($data);
        exit;
    }
    /**
     * @NodeAnotation(title="设置短期选项")
     */
    public function xuanxiang(){
        $url = url('nursinguser.optiontype/index?field=nursing_lang_id&id=8')->build();
        return $this->redirect($url);
    }
    /**
     * @NodeAnotation(title="短期病症设置")
     */
    public function shezi(){
        $url = url('nursinguser.changqihuli/index?field=nursing_lang_id&id=8')->build();
        return $this->redirect($url);
    }
    public function changqi(){
        $id = $this->request->param('id');
        $data = $this->request->param();
        if(isset($data['nursing_lang_id'])&&$data['nursing_lang_id']){
            $nursing_lang_id = $data['nursing_lang_id'];
            $newdata = [];
            $newdata_id = [];
            foreach ($data as $key=>$value){
                if(strpos($key,'key')!==false){
                    $key = str_replace('key','',$key);
                    foreach ($value as $v){
                        $has = TermEmergencyLang::where('status',1)
                            ->where('nursing_lang_id',$data['nursing_lang_id'])
                            ->where('nursing_type_id',$key)
                            ->where('nursing_id',$v)
                            ->findOrEmpty()->toArray();
                        if(empty($has)){
                            $newdata[] = [
                                'nursing_lang_id'=>$nursing_lang_id,
                                'nursing_type_id'=>$key,
                                'nursing_id'=>$v,
                                'status'=>1,
                                'create_time'=>time(),
                                'update_time'=>time(),
                            ];
                        }else{
                            $newdata_id[] = $has['id'];
                        }
                    }
                }
            }
//            echo '<pre>';
//            print_r($nursing_lang_id);
//            print_r($newdata_id);
//            exit;
            $bo = Db::name('term_emergency_lang')->where('nursing_lang_id',$nursing_lang_id)
                ->whereNotIn('id',$newdata_id)
                ->delete();
            if(!empty($newdata)){
                $bool = Db::name('term_emergency_lang')
                    ->insertAll($newdata);
                if(!$bool){
                    return $this->error('修改失败');
                }
            }
            return $this->success('修改成功');
        }else{
            $nursing_type = NursingType::where('status',1)
                ->order('sort desc')
                ->select()->toArray();
            $fetch = Quickbuilder::makeForm()
                ->setAction()
                ->set_up_form('none','','nursing_lang_id',$id);
            $youde = TermEmergencyLang::where('status',1)
                ->where('nursing_lang_id',$id)
                ->column('nursing_id');
//            echo '<pre>';
//            print_r($youde);
//            exit;
            if(!empty($youde)){
                $youde = implode(',',$youde);
            }
            foreach ($nursing_type as $value){
                $child = \app\admin\model\Nursing::where('status',1)
                    ->where('type',$value['id'])
                    ->order('sort desc')
                    ->select()->toArray();
//                echo '<pre>';
//                print_r($child);
//                exit;
                $fetch = $fetch->set_up_form('lcheckbox',$value['name'],'key'.$value['id'],$youde,$child,'',1,['value'=>'id','show'=>'name']);
            }
            $fetch = $fetch->set_button('submit','提交')
                ->fetch();
            return $fetch;
        }
    }
}